package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.security.annotation.GuiGuCache;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.api.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.service.IProductSkuService;
import com.spzx.product.service.ISkuStockService;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author lee
 * @since 2024-07-15
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ProductDetailsMapper productDetailsMapper;
    @Autowired
    private ProductSkuMapper productSkuMapper;
    @Autowired
    private SkuStockMapper skuStockMapper;

    @Autowired
    private ISkuStockService skuStockService;

    @Autowired
    private IProductSkuService productSkuService;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public List<Product> getProductList(Product product) {

        return baseMapper.getProductList(product);
    }

    @Override
    public Integer updateAuditStatus(Long id, Integer auditStatus) {
        Product product = new Product();
        product.setId(id);
        if (auditStatus == 1) {
            product.setAuditStatus(1);
            product.setAuditMessage("审批通过");
        } else if (auditStatus == -1) {
            product.setAuditStatus(-1);
            product.setAuditMessage("驳回");
        } else {
            throw new IllegalArgumentException("参数不合法");
        }
        return baseMapper.updateById(product);
    }

    @Override
    public Integer updateStatus(Long id, Integer status) {

        Product product = new Product();
        product.setId(id);
        if (status == 1) {
            RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("sku:bloom:filter");
            List<ProductSku> productSkuList = productSkuMapper.selectList(
                    new LambdaQueryWrapper<ProductSku>()
                            .select(ProductSku::getId).eq(ProductSku::getProductId,id)
            );
            productSkuList.forEach(item->{
                bloomFilter.add(item.getId());
            });

            product.setStatus(1);
        } else if (status == -1) {
            String dataKey = "Product:"+id;
            redisTemplate.delete(dataKey);
            product.setStatus(-1);
        } else {
            throw new IllegalArgumentException("参数不合法");
        }
        return baseMapper.updateById(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addProduct(Product product) {
        baseMapper.insert(product);
        //保存图片详情列表
        String imageUrls = null;
        List<String> detailsImageUrlList = product.getDetailsImageUrlList();
        if (detailsImageUrlList != null) {
            imageUrls = String.join(",", detailsImageUrlList);
        }
        ProductDetails productDetails = new ProductDetails();
        productDetails.setProductId(product.getId());
        productDetails.setImageUrls(imageUrls);
        productDetailsMapper.insert(productDetails);

        //保存skuList
        List<ProductSku> productSkuList = product.getProductSkuList();
        for (int i = 0; i < productSkuList.size(); i++) {
            //保存skuList
            ProductSku productSku = productSkuList.get(i);
            productSku.setProductId(product.getId());
            productSku.setSkuCode(product.getId() + "_" + i);
            productSku.setSkuName(product.getName() + " " + productSku.getSkuSpec());
            productSkuMapper.insert(productSku);

            //保存库存
            SkuStock skuStock = new SkuStock();
            skuStock.setSkuId(productSku.getId());
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setAvailableNum(productSku.getStockNum());
            skuStock.setLockNum(0);
            skuStock.setSaleNum(0);
            skuStockMapper.insert(skuStock);
        }

        return 1;
    }

    @Override
    public Product getDetailById(Integer id) {
        //查询商品详情
        Product product = baseMapper.selectById(id);

        //查询商品的库存和skuId
        List<SkuStock> numAndSkuId = skuStockMapper.getTotalNumAndSkuIdByProductId(id);
        Map<Long, Integer> numAndSkuIdMap = numAndSkuId.stream().collect(Collectors.toMap(SkuStock::getSkuId, SkuStock::getTotalNum));

        //查询商品的sku列表
        List<ProductSku> productSkuList = productSkuMapper.selectList(
                new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id)
        );
        for (ProductSku productSku : productSkuList) {
            productSku.setStockNum(numAndSkuIdMap.get(productSku.getId()));
        }
        product.setProductSkuList(productSkuList);
        //查询商品的图片详情列表
        String imageUrls = productDetailsMapper.getDetailsImageUrl(id);
        String[] split = imageUrls.split(",");
        product.setDetailsImageUrlList(Arrays.stream(split).toList());
        return product;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateProduct(Product product) {
        //更新商品属性
        String productKey = "Product:"+product.getId();
        redisTemplate.delete(productKey);
        baseMapper.updateById(product);

        //更新商品的图片详情
        ProductDetails productDetails = productDetailsMapper.selectOne(
                new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, product.getId())
        );
        String imageUrls = null;
        List<String> detailsImageUrlList = product.getDetailsImageUrlList();
        if (detailsImageUrlList != null) {
            imageUrls = String.join(",", detailsImageUrlList);
        }
        productDetails.setImageUrls(imageUrls);
        productDetailsMapper.updateById(productDetails);

        //更新skuStock
        List<ProductSku> productSkuList = product.getProductSkuList();
        Map<Long, Integer> skuIdAndTotalNum = productSkuList.stream().collect(Collectors.toMap(ProductSku::getId, ProductSku::getStockNum));
        List<SkuStock> skuStockList = skuStockMapper.selectList(
                new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, skuIdAndTotalNum.keySet()));
        for (SkuStock skuStock : skuStockList) {
            skuStock.setTotalNum(skuIdAndTotalNum.get(skuStock.getId()));
            skuStock.setUpdateBy(SecurityUtils.getUsername());
            skuStock.setUpdateTime(new Date());
        }
        skuStockService.updateBatchById(skuStockList);


        //更新商品的sku
        for (ProductSku productSku : productSkuList) {
            productSku.setUpdateBy(SecurityUtils.getUsername());
            String skuKey = "ProductSku:"+productSku.getId();
            redisTemplate.delete(skuKey);
        }
        productSkuService.updateBatchById(productSkuList);



        return 1;
    }

    @Override
    public int removeProduct(List<Long> ids) {
        for (Long id : ids) {
            String productKey = "Product:" + id;
            redisTemplate.delete(productKey);
        }
        //查询productSkuId
        List<Long> productSkuIds = productSkuMapper.selectProductSkuId(ids);
        for (Long productSkuId : productSkuIds) {
            String productSkuKey = "ProductSku:" + productSkuId;
            redisTemplate.delete(productSkuKey);
        }
        //查询skuStockId
        List<Long> skuStockIds = skuStockMapper.selectSkuStockId(productSkuIds);
        //查询商品详情的id
        List<Long> productDetailsIds = productDetailsMapper.selectProductDetailsId(ids);

        baseMapper.deleteBatchIds(ids);
        productSkuMapper.deleteBatchIds(productSkuIds);
        skuStockMapper.deleteBatchIds(skuStockIds);
        productDetailsMapper.deleteBatchIds(productDetailsIds);
        return 1;
    }

    @Override
    @GuiGuCache(prefix = "SkuSpecValue:")
    public Map<String, Long> getSkuSpecValue(Long id) {
        Map<String, Long> map = new HashMap();
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getProductId,id).select(ProductSku::getId, ProductSku::getSkuSpec);
        List<ProductSku> productSkuList = productSkuMapper.selectList(queryWrapper);
        for (ProductSku productSku : productSkuList) {
            map.put(productSku.getSkuSpec(),productSku.getId());
        }

        return map;
    }


    @GuiGuCache(prefix = "Product:")
    @Override
    public Product getProductById(Integer id) {
        return baseMapper.selectById(id);
    }

}
